package org.example;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

/**
 * https://www.jb51.net/article/219721.htm
 * 基于jdk1.8实现任务异步处理  真正的异步
 *
 *
 *
 * @author Administrator
 */
public class Java8RealAsync {
    public static void main(String[] args) throws Throwable, ExecutionException {
        // 两个线程的线程池
        ExecutorService executor = Executors.newCachedThreadPool();
        //jdk1.8的实现方式
        CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                Long _long = 0L;
                System.out.println("task线程开始了,线程是"+Thread.currentThread().getName());
                try {
                    //模拟耗时操作
                    long start = System.currentTimeMillis();
                    for (long i = 0; i <= 99_999_999L; i++) {
                        Random random = new Random();
                        int seed = random.nextInt(100);
                        Random random1 = new Random(seed);
                        int i1 = random1.nextInt(100);
                        _long = i1 + _long;
                    }
                    long end = System.currentTimeMillis();
                    System.out.println("程序耗时:" + (end - start) + "毫秒-----运行结果是:"+_long);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "task成功返回值"+_long;
            }
        }, executor);

        //采用lambada的实现方式
        future.thenAccept( e -> {
            System.out.println(e + " ok.线程是:"+Thread.currentThread().getName());
            new Java8RealAsync().callBack(e);
        });

        System.out.println("主线程结束了");
    }

    public void callBack(String response) {
        System.out.println("callBack方法执行了,response:"+response +"---线程是:"+Thread.currentThread().getName());
    }
}
